import React, { PureComponent } from 'react'

export class App extends PureComponent {
  constructor() {
    super()
    this.state = {
      isAgree: false,
      hobbies: [
        { name: '跳舞', value: 'dance', isChecked: false },
        { name: '唱歌', value: 'sing', isChecked: false },
        { name: '跑步', value: 'run', isChecked: false },
      ]
    }
  }
  handleCheck(e) {
    this.setState({ isAgree: e.target.checked })
  }
  handleSubmit() {
    const { isAgree, hobbies } = this.state
    console.log(isAgree)
    console.log(hobbies.filter(i => i.isChecked).map(i => i.value))
  }
  handleCheckbox(e, index) {
    let hobbies = [...this.state.hobbies]
    hobbies[index].isChecked = e.target.checked
    this.setState({ hobbies })
  }
  render() {
    const { isAgree, hobbies } = this.state
    return (
      <div>
        <label htmlFor="agree">
          <input type="checkbox" id="agree" name="isAgree" checked={isAgree} onChange={e => this.handleCheck(e)} /> 同意协议
        </label>
        <div>
          爱好：
          {
            hobbies.map((item, index) => {
              return (
                <label htmlFor={item.value} key={item.value}>
                  <input type="checkbox" id={item.value} name={item.value} checked={item.isChecked} onChange={e => this.handleCheckbox(e, index)} />{ item.name }
                </label>
              )
            })
          }
        </div>
        <button onClick={() => this.handleSubmit()}>提交</button>
      </div>
    )
  }
}

export default App